package org.opu.odg.dg.runtimedata;

import org.apache.commons.lang.StringUtils;
import org.opu.odg.dg.incomingdata.GlobalVariables;

/**
 * This instance must be one on all generation process
 * @author yura
 */
public class VariableHolder {

    private Content content;
    private GlobalVariables vars;

    public VariableHolder(Content content, GlobalVariables vars) {
        this.content = content;
        this.vars = vars;
    }

    public void setContent(Content content) {
        this.content = content;
    }

    public Content getContent() {
        return content;
    }

    public String getVarValue(String name) {
        int indexOf = name.indexOf('.');
        String var = null;
        if (indexOf != -1) {
            String cName = name.substring(0, indexOf);
            name = name.substring(indexOf, name.length());
            Content c = content;
            while (c != null) {
                if (c.getName().equals(cName)) {
                    var = c.getLastIteration().get(name);
                    break;
                }
                c = c.getParent();
            }
        } else {
            Content c = content;
            while (c != null) {
                if (c.isContextIterationAvailable() && (var = c.getLastIteration().get(name)) != null) {
                    break;
                }
                c = c.getParent();
            }
            if (StringUtils.isEmpty(var)) {
                var = vars.get(name);
            }
        }
        return var != null ? var : "";
    }
}
